package lucene.server.common.datasource;
import lombok.extern.slf4j.Slf4j;

import java.io.Closeable;
import java.io.PrintWriter;
import java.sql.*;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Logger;
import javax.sql.DataSource;


@Slf4j
public class PooledDataSource implements DataSource, Closeable {
    private String name;
    private String url;
    private String username;
    private String password;
    private String driverClass;
    private String dbType;

    //连接创建时间
    private long createTime = 0;
    //开始使用的时间,超过一定时间释放
    private long useStartTime = 0;
    private long lastUseTime = 0;
    //上次验证时间
    private long validateTime = 0;
    private String validateSql;
    private Connection conn;
    //false--空闲，true--忙不可使用
    private boolean busy = false;

    public PooledDataSource(String name,String url, String username, String password, String driverClass,String dbType) {
        this.name = name;
        this.url = url;
        this.username = username;
        this.password = password;
        this.driverClass = driverClass;
        this.dbType = dbType;
        this.createByThread();
    }

    public void createByThread(){
        try {
           Class.forName(this.driverClass);//加载驱动
           this.conn = DriverManager.getConnection(this.url,this.username,this.password);
           this.validateSql = PoolConfig.getValidateSql(this.dbType);
        } catch (Exception e ) {
           System.out.format("\33[31;1m31:%s%n",e.getMessage());
        }
        createTime = System.currentTimeMillis();

    }

    public boolean modifyConnection(String name,String url, String username, String password, String driverClass,String dbType) {
        this.name = name;
        this.url = url;
        this.username = username;
        this.password = password;
        this.driverClass = driverClass;
        this.dbType = dbType;
        this.createByThread();
        return true;
    }

    public Connection getConnection() {
        this.busy = true;
        this.useStartTime = System.currentTimeMillis();
        this.lastUseTime = System.currentTimeMillis();
        return conn;
    }

    public boolean isBusy() {
        return busy;
    }

    //释放连接池中的连接对象
    public void release(){
        this.useStartTime = 0L;
        this.lastUseTime = System.currentTimeMillis();
        this.busy = false;
    }

    @Override
    public void close(){
        try {
            if(this.conn!=null && !this.conn.isClosed()){
                this.conn.close();
            }
        } catch (SQLException e) {
            System.out.format("\33[31;1m31:%s%s%n",this.name,e.getMessage());
        }
    }
    /*自动释放数据库连接*/
    public  void autoRelease() {
        if(this.useStartTime ==0){
            return;
        }
        if((new Date().getTime()  - this.useStartTime)>PoolConfig.getPoolTimeout()){
            this.release();
        }
    }
    /*定时检测数据库连接*/
    public  void validateConnection() {
        if(this.validateSql == null || this.validateSql.isEmpty()){
            return;
        }

        if(this.busy){  return; }

        if(System.currentTimeMillis()-validateTime<PoolConfig.getValidateTimeMillis()){
            return;
        }

        this.validateTime = System.currentTimeMillis();

        Statement stmt = null;
        try {
            if (this.conn.isClosed()) {
                this.createByThread();
                return;
            }
            stmt = conn.createStatement();
            stmt.execute(this.validateSql);
            return;
        } catch (SQLException e) {
            this.createByThread();
            System.out.format("\33[31;1m31:%s%s%n",this.name,e.getMessage());
        } finally {
            if (stmt == null) {
                return;
            }
            try {
                stmt.close();
            } catch (Exception e) {
            }
        }

    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return null;
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return null;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return null;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {

    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {

    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return 0;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return null;
    }

    public Map<String,Object>  getConnectionInfo() throws SQLException {
        Map<String,Object> connInfo = new LinkedHashMap<>();
        connInfo.put("createTime",createTime);
        connInfo.put("lastUseTime",lastUseTime);
        connInfo.put("validateTime",validateTime);
        connInfo.put("busy",busy);
        connInfo.put("isClose",conn.isClosed());
        return connInfo;
    }
    public Map<String,Object>  getProductInfo() throws SQLException {
        Map<String,Object> productInfo = new LinkedHashMap<>();
        productInfo.put("DriverName",conn.getMetaData().getDriverName());
        productInfo.put("DriverVersion",conn.getMetaData().getDriverVersion());
        productInfo.put("DatabaseProductName",conn.getMetaData().getDatabaseProductName());
        productInfo.put("DatabaseProductVersion",conn.getMetaData().getDatabaseMajorVersion());
        return productInfo;
    }
    public String getName() {
        return name;
    }
    public String getDbType() {
        return dbType;
    }
}
